import React, { useRef, useEffect } from "react";
import { Form, Input, Button } from "antd";
import { useDispatch } from "react-redux";
import cls from "classnames";
import Router from "next/router";

import style from "./index.module.scss";
import { MCountDown } from "@/components/CountDown";
import { useAuth } from "@/hooks/useAuth";
import { NextPage } from "next";

const Signup: NextPage = () => {
  /**
   * use dispatch redux action
   */
  const dispatch = useDispatch();

  /**
   * get auth info
   */
  const auth = useAuth();

  /**
   * antd 4.x 表单实例
   */
  const [form] = Form.useForm();

  /**
   * counter ref instance
   */
  const countRef = useRef<null | any>();

  /**
   * Judge user information
   */
  useEffect(() => {
    if (auth?.id) {
      Router.replace("/");
    }
  }, [auth]);

  /**
   * 注册
   * @param values 用户信息
   */
  const signup = (values) => {
    console.log("info", values);
  };

  /**
   * 发送验证码
   */
  const sendCode = () => {
    return new Promise(async (resolve, reject) => {
      resolve();
    });
  };
  return (
    <div className={cls(style.wrapper, "container")}>
      <div className={style.formBox}>
        <Form onFinish={signup} form={form}>
          <Form.Item
            label="用户名"
            name="name"
            rules={[
              {
                required: true,
                message: "Please input your nickname",
              },
            ]}
          >
            <Input size="large" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="pwd"
            rules={[
              {
                required: true,
                message: "Please input your nickname",
              },
            ]}
          >
            <Input.Password size="large" />
          </Form.Item>

          <Form.Item
            label="验证码"
            name="code"
            rules={[
              {
                required: true,
                message: "Please input your nickname",
              },
            ]}
          >
            <Input
              size="large"
              addonAfter={
                <MCountDown
                  cref={countRef}
                  count={10}
                  next="s后重试"
                  onStart={sendCode}
                />
              }
            />
          </Form.Item>
          <Form.Item>
            <Button size="large" htmlType="submit">
              注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Signup;
